#include"buffer.h"

_FILE* _fopen(const char* file_name, const char* file_mode)
{
    int fd = -1;
    if(strcmp(file_mode, "r") == 0)
    {
        fd = open(file_name, O_RDONLY);
    }
    else if(strcmp(file_mode, "w") == 0)
    {
        fd = open(file_name, O_WRONLY | O_CREAT | O_TRUNC, CREATE_PERM);
    }
    else if(strcmp(file_mode, "a") == 0)
    {
        fd = open(file_name, O_WRONLY | O_CREAT | O_APPEND, CREATE_PERM);
    }
    else 
    {
        return NULL;
    }

    if(fd != -1)
    {
        _FILE* fp = (_FILE*)malloc(sizeof(_FILE));
        fp->_fd = fd;
        fp->_pos = 0;
        fp->_flag = FLASH_LINE; 
        return fp;
    }

    return NULL;
}

void _fclose(_FILE* fp)
{
    close(fp->_fd);
    free(fp);
}

void _fflush(_FILE* fp)
{
    if(fp->_pos > 0)
    {
        write(fp->_fd, fp->_buffer, fp->_pos);
        fp->_pos = 0;
    }
}

int _fwrite(const char* str, int len, _FILE* fp)
{
    if(fp->_flag == FLASH_LINE)
    {
        //先往缓冲区写，然后遇到'\n'再写入
        memcpy(fp->_buffer + fp->_pos, str, len);
        fp->_pos += len;
        if(fp->_buffer[fp->_pos - 1] == '\n')
        {
            write(fp->_fd, fp->_buffer, fp->_pos);
            int ret = fp->_pos;
            fp->_pos = 0;
            return ret;
        }
    }
    else if(fp->_flag == FLASH_ALL)
    {
        int ret = 0;
        if(fp->_pos + len >= SIZE)
        {
            write(fp->_fd, fp->_buffer, fp->_pos);
            ret = fp->_pos;
            fp->_pos = 0;
        }
        memcpy(fp->_buffer + fp->_pos, str, len);
        fp->_pos += len;
        return ret;
    }
    else 
    {
        write(fp->_fd, str, len);
    }

    return  0;
}
